//
//  RBHomeNoticeView.m
//  zhongzhenglu
//
//  Created by XL on 2022/5/26.
//

#import "RBHomeNoticeView.h"
#import <Masonry.h>
#import <iCarousel.h>
#import "RanTool.h"
#import "RBTimer.h"
#import <YYCategories.h>

@interface RBHomeNoticeView()<iCarouselDataSource, iCarouselDelegate>

@property(nonatomic, strong) RBTimer *timer;
@property(nonatomic, strong) iCarousel *carousel;

@end

@implementation RBHomeNoticeView

#pragma mark - Lifecycle

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setup];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setup];
    }
    return self;
}

- (void)setup
{
    iCarousel *view = [iCarousel new];
    self.carousel = view;
    view.scrollEnabled = NO;
    view.vertical = YES;
    view.pagingEnabled = YES;
    view.clipsToBounds = YES;
    view.dataSource = self;
    view.delegate = self;
    [self addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    self.timer = RBTimer.new;
    [self.timer startTimerWithInterval:5 block:^(float countF, NSInteger countI) {
        [weakSelf timerEvent];
    }];
}

#pragma mark - Event

- (void)timerEvent
{
    NSInteger index = [self.carousel currentItemIndex] + 1;
    if (index >= self.data.count) {
        index = 0;
    }
    [self.carousel scrollToItemAtIndex:index animated:YES];
}

#pragma mark - iCarouselDataSource & Delegate

- (NSInteger)numberOfItemsInCarousel:(__unused iCarousel *)carousel
{
    return self.data.count;
}

- (UIView *)carousel:(__unused iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
    UILabel *mView = (UILabel *)view;
    if (!mView)
    {
        mView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, carousel.frame.size.width, carousel.frame.size.height)];
        mView.textColor = [UIColor colorWithHexString:@"#4D4948"];
        mView.font = [UIFont systemFontOfSize:Zoom(14)];
    }
    mView.frame = CGRectMake(0, 0, carousel.frame.size.width, carousel.frame.size.height);
    mView.text = self.data[index];
    return mView;
}

- (CGFloat)carousel:(__unused iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
    switch (option)
    {
        case iCarouselOptionWrap:
        {
            return YES;
        }
            break;
        default:
            return value;
            break;
    }
}

- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
    
}

#pragma mark - Setter

- (void)setData:(NSArray *)data
{
    _data = data;
    [self.carousel reloadData];
}

#pragma mark - Getter

- (NSInteger)currentIndex
{
    return self.carousel.currentItemIndex;
}

@end
